// 日期选择弹窗组件
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 弹窗显示状态
    visible: {
      type: Boolean,
      value: false
    },
    // 默认选中的开始日期
    defaultStartDate: {
      type: String,
      value: ''
    },
    // 默认选中的结束日期
    defaultEndDate: {
      type: String,
      value: ''
    },
    // 最小可选日期（默认为今天）
    minDate: {
      type: String,
      value: ''
    },
    // 最大可选日期
    maxDate: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 星期表头
    weekDays: ['日', '一', '二', '三', '四', '五', '六'],
    // 当前显示的年月
    currentYear: 2025,
    currentMonth: 1,
    // 日历数据
    calendarData: [],
    // 选中的开始日期
    startDate: '',
    // 选中的结束日期
    endDate: '',
    // 是否可以确定
    canConfirm: false
  },

  /**
   * 组件生命周期
   */
  lifetimes: {
    attached() {
      this.initCalendar();
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 初始化日历
     */
    initCalendar() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      
      this.setData({
        currentYear: year,
        currentMonth: month,
        startDate: this.properties.defaultStartDate,
        endDate: this.properties.defaultEndDate
      });

      this.generateCalendarData(year, month);
      this.updateConfirmStatus();
    },

    /**
     * 生成日历数据
     */
    generateCalendarData(year, month) {
      const firstDay = new Date(year, month - 1, 1);
      const lastDay = new Date(year, month, 0);
      const firstDayWeek = firstDay.getDay();
      const daysInMonth = lastDay.getDate();
      
      const today = new Date();
      const todayStr = this.formatDate(today);
      const tomorrowStr = this.formatDate(new Date(today.getTime() + 24 * 60 * 60 * 1000));
      const dayAfterTomorrowStr = this.formatDate(new Date(today.getTime() + 48 * 60 * 60 * 1000));
      
      // 获取最小日期
      const minDate = this.properties.minDate || todayStr;
      
      const calendarData = [];
      let week = [];
      
      // 填充上个月的空白日期
      for (let i = 0; i < firstDayWeek; i++) {
        week.push({ day: '', date: '', disabled: true, topLabel: '', bottomLabel: '' });
      }
      
      // 填充当月日期
      for (let day = 1; day <= daysInMonth; day++) {
        const dateStr = this.formatDate(new Date(year, month - 1, day));
        const isDisabled = dateStr < minDate;
        
        // 上方标签：今天、明天、后天
        let topLabel = '';
        if (dateStr === todayStr) {
          topLabel = '今天';
        } else if (dateStr === tomorrowStr) {
          topLabel = '明天';
        } else if (dateStr === dayAfterTomorrowStr) {
          topLabel = '后天';
        }
        
        // 检查是否为选中的日期
        const isStart = dateStr === this.data.startDate;
        const isEnd = dateStr === this.data.endDate;
        const inRange = this.isInRange(dateStr);
        
        // 下方标签：入住、离店
        let bottomLabel = '';
        if (isStart) {
          bottomLabel = '入住';
        } else if (isEnd) {
          bottomLabel = '离店';
        }
        
        week.push({
          day: day,
          date: dateStr,
          disabled: isDisabled,
          topLabel: topLabel,
          bottomLabel: bottomLabel,
          isStart: isStart,
          isEnd: isEnd,
          inRange: inRange
        });
        
        // 每周7天，换行
        if (week.length === 7) {
          calendarData.push(week);
          week = [];
        }
      }
      
      // 填充下个月的空白日期
      if (week.length > 0) {
        while (week.length < 7) {
          week.push({ day: '', date: '', disabled: true, topLabel: '', bottomLabel: '' });
        }
        calendarData.push(week);
      }
      
      this.setData({ calendarData });
    },

    /**
     * 判断日期是否在选中范围内
     */
    isInRange(dateStr) {
      if (!this.data.startDate || !this.data.endDate) {
        return false;
      }
      return dateStr > this.data.startDate && dateStr < this.data.endDate;
    },

    /**
     * 格式化日期为 YYYY-MM-DD
     */
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    /**
     * 日期点击事件
     */
    onDateTap(e) {
      const { date, disabled } = e.currentTarget.dataset;
      
      if (!date || disabled) {
        return;
      }
      
      const { startDate, endDate } = this.data;
      
      if (!startDate || (startDate && endDate)) {
        // 选择开始日期
        this.setData({
          startDate: date,
          endDate: ''
        });
      } else if (startDate && !endDate) {
        // 选择结束日期
        if (date > startDate) {
          this.setData({
            endDate: date
          });
        } else {
          // 如果选择的日期早于开始日期，重新选择开始日期
          this.setData({
            startDate: date,
            endDate: ''
          });
        }
      }
      
      // 重新生成日历数据
      this.generateCalendarData(this.data.currentYear, this.data.currentMonth);
      this.updateConfirmStatus();
    },

    /**
     * 更新确认按钮状态
     */
    updateConfirmStatus() {
      const canConfirm = !!(this.data.startDate && this.data.endDate);
      this.setData({ canConfirm });
    },

    /**
     * 遮罩层点击事件
     */
    onMaskTap() {
      this.onClose();
    },

    /**
     * 弹窗内容点击事件（阻止冒泡）
     */
    onPopupTap() {
      // 阻止事件冒泡到遮罩层
    },

    /**
     * 关闭弹窗
     */
    onClose() {
      this.triggerEvent('close');
    },

    /**
     * 确认选择
     */
    onConfirm() {
      if (!this.data.canConfirm) {
        return;
      }
      
      this.triggerEvent('confirm', {
        startDate: this.data.startDate,
        endDate: this.data.endDate
      });
    },

    /**
     * 上一月
     */
    onPrevMonth() {
      let { currentYear, currentMonth } = this.data;
      
      // 不允许选择当前月份之前的月份
      const now = new Date();
      const currentYearMonth = now.getFullYear() * 12 + now.getMonth();
      const targetYearMonth = currentYear * 12 + (currentMonth - 2); // currentMonth-1是当前显示月份，再-1是上一月
      
      if (targetYearMonth < currentYearMonth) {
        return;
      }
      
      currentMonth--;
      if (currentMonth < 1) {
        currentMonth = 12;
        currentYear--;
      }
      
      this.setData({
        currentYear,
        currentMonth
      });
      
      this.generateCalendarData(currentYear, currentMonth);
    },

    /**
     * 下一月
     */
    onNextMonth() {
      let { currentYear, currentMonth } = this.data;
      
      currentMonth++;
      if (currentMonth > 12) {
        currentMonth = 1;
        currentYear++;
      }
      
      this.setData({
        currentYear,
        currentMonth
      });
      
      this.generateCalendarData(currentYear, currentMonth);
    }
  }
})